import { usePersistStore } from "@/stores";
import { storeToRefs } from "pinia";
import { createRouter, createWebHistory } from "vue-router";

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: "/login",
      component: () => import("@/views/LoginPage.vue"),
    },
    {
      path: "/",
      component: () => import("@/views/LayoutPage.vue"),
      redirect: "/desk",
      children: [
        {
          path: "/desk",
          component: () => import("@/views/WorkDesk.vue"),
        },
        {
          path: "/tobacco/manage",
          component: () => import("@/views/TobaccoManage.vue"),
        },
        {
          path: "/tobacco/extra",
          component: () => import("@/views/TobaccoExtra.vue"),
        },
        {
          path: "/tobacco/group",
          component: () => import("@/views/TobaccoGroup.vue"),
        },
        {
          path: "/tobacco/short",
          component: () => import("@/views/TobaccoShort.vue"),
        },
        {
          path: "/user/manage",
          component: () => import("@/views/UserManage.vue"),
        },
        {
          path: "/user/password",
          component: () => import("@/views/UserPassword.vue"),
        },
      ],
    },
  ],
});

//登录访问的拦截
router.beforeEach((to) => {
  const persistStore = usePersistStore();
  const { userInfo } = storeToRefs(persistStore);
  if (!userInfo.value.token && to.path !== "/login") return "/login";
});

export default router;
